package cn.edu.scau.cmi.wujiaming.hibernate.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import cn.edu.scau.cmi.wujiaming.hibernate.domain.Teacher;
import cn.edu.scau.cmi.wujiaming.hibernate.hibernateUtil.HibernateUtil;



public class TeacherDAO{
	
	public  static boolean save(Teacher  teacher) {
		Session session = HibernateUtil.getSession();
		Transaction  transaction = session.beginTransaction();
		Query<Teacher>  query  = session.createQuery("from Teacher where name = \'" + teacher.getName() +"\'");
		Teacher existedTeacher = query.uniqueResult();
		if(existedTeacher != null) {
			transaction.commit();
			session.close();
			return  false;
		}
		session.save(teacher);
		transaction.commit();
		session.close();
		return true;
	}
	
	public static void delete(Teacher  teacher) {
		Session session = HibernateUtil.getSession();
		Transaction  transaction = session.beginTransaction();
		session.delete(teacher);
		transaction.commit();
		session.close();
	}
	
	public static Teacher findTeacherByName(String name) {
		Session session = HibernateUtil.getSession();
		Transaction  transaction = session.beginTransaction();
		Query<Teacher>  query  = session.createQuery("from Teacher where name  = \'" + name +"\'");
		Teacher teacher = query.uniqueResult();
		transaction.commit();
		session.close();
		return teacher;
	}
	
	public static Teacher  update(Teacher  teacher) {
		Session session = HibernateUtil.getSession();
		Transaction  transaction = session.beginTransaction();
		session.saveOrUpdate(teacher);
		transaction.commit();
		session.close();
		return teacher;
	}
	
	public static List<Teacher>  findAllTeacher(){
		Session session = HibernateUtil.getSession();
		Transaction  transaction = session.beginTransaction();
		Query<Teacher>  query  = session.createQuery("from Teacher");
		List<Teacher> teachers = query.getResultList();
		transaction.commit();
		session.close();
		return teachers;
	}
	
}
